<script setup>
import { computed, reactive, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  data: {
    type: Array,
    default: () => []
  },
  itemKey: {
    type: String,
    default: 'value'
  },
  labelKey: {
    type: String,
    default: 'label'
  },
  valueKey: {
    type: String,
    default: 'value'
  }
})

const emits = defineEmits(['update:modelValue', 'change'])

const form = reactive({
  value: 0
})

watch(
  () => props.modelValue,
  (value) => {
    form.value = value
  },
  { immediate: true }
)

const radios = computed(() => {
  return props.data
})
const itemKey = computed(() => {
  return props.itemKey
})
const labelKey = computed(() => {
  return props.labelKey
})
const valueKey = computed(() => {
  return props.valueKey
})
const onSelect = function (e) {
  form.value = e.detail.value
  emits('update:modelValue', form.value)
  emits('change', form.value)
}
</script>

<template>
  <div class="custom-radio-group-container">
    <radio-group class="radio-group rounded" @change="onSelect">
      <template v-for="item in radios" :key="item[itemKey]">
        <label :class="['label', item[valueKey] === form.value ? 'checked' : '']">
          <radio class="radio__input" :value="item[valueKey]"></radio>
          <span class="radio__label"> {{ item[labelKey] }}</span>
        </label>
      </template>
    </radio-group>
  </div>
</template>

<style scoped lang="scss">
.custom-radio-group-container {
  .radio-group {
    display: flex;

    &.rounded {
      .label {
        margin: 0;
        padding: 0;

        &.checked {
          .radio__label {
            color: #1b96ff;
            border-radius: 40px 40px 40px 40px;
            border: 1px solid #1b96ff;
          }
        }
      }

      .radio__input {
        display: none;
      }

      .radio__label {
        font-size: 14px;
        color: #666;
        border-radius: 40px 40px 40px 40px;
        border: 1px solid #dddddd;
        min-width: 90rpx;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 8rpx;
        padding: 6rpx 8rpx;
      }
    }
  }
}
</style>
